#include "qstylesheetproperty.h"

#include "../../libs/sharedLib/stylesheet/stylesheetstruct.h"
#include "../../libs/sharedLib/qbtneditorlabel.h"
#include "../../libs/sharedLib/stylesheet/qstylesheetitemfactory.h"
#include "../../libs/sharedLib/stylesheet/qabstractstylesheetitem.h"

QStylesheetProperty::QStylesheetProperty(SHAREDLIB::QAbstractProperty *parent):
    SHAREDLIB::QAbstractProperty(parent)
{
    this->setAttribute("reset",false);
}

QStylesheetProperty::~QStylesheetProperty()
{
}

QString QStylesheetProperty::valueText()
{
    return tr("Clicked for more");
}

void QStylesheetProperty::valueXML(QXmlStreamWriter *w)
{
    tagStylesheetItems items=m_value.value<tagStylesheetItems>();

    SHAREDLIB::QAbstractStylesheetItem *maker=SHAREDLIB::QStylesheetItemFactory::createItem(attribute("name").toString());
    if(maker!=NULL)
    {
        foreach(tagStylesheetItem item,items)
        {
            QVariant v;
            v.setValue<tagStylesheetItem>(item);
            maker->setProperty("type",item.m_attributes.value("type").toString());
            maker->setValue(v);
            maker->write(w);
        }

        delete maker;
    }
}

void QStylesheetProperty::parserXML(QXmlStreamReader *r)
{
    foreach(const QXmlStreamAttribute &attribute,r->attributes())
    {
        if(m_saveAttributes.keys().contains(attribute.name().toString()))
        {
            m_saveAttributes.insert(attribute.name().toString(),attribute.value().toString());
        }
    }

    SHAREDLIB::QAbstractStylesheetItem *maker=SHAREDLIB::QStylesheetItemFactory::createItem(attribute("name").toString());
    if(maker==NULL)
    {
        r->raiseError("error!");
        return;
    }
    tagStylesheetItems items;

    for(bool finished=false;!finished && !r->hasError();)
    {
        switch(r->readNext())
        {
        case QXmlStreamReader::StartElement:
            {
                tagStylesheetItem item;
                maker->clear();
                maker->read(r);
                item=maker->value().value<tagStylesheetItem>();
                item.m_attributes.insert("type",r->name().toString());
                items.append(item);
            }
             break;
        case QXmlStreamReader::EndElement:
            finished=true;
            break;
        case QXmlStreamReader::Characters:
            break;
        default:
            break;
        }
    }
    delete maker;
    QVariant v;
    v.setValue<tagStylesheetItems>(items);
    setValue(v);
}

QWidget* QStylesheetProperty::getEditor()
{
    if(attribute("editabled").toBool())
    {
        m_editor=new SHAREDLIB::QBtnEditorLabel(this);
    }
    return QAbstractProperty::getEditor();
}

void QStylesheetProperty::setValue(const QVariant &value)
{
    SHAREDLIB::QAbstractProperty::setValue(value);
}
